package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcShiftsMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcPlan;
import com.csun.cmny.provider.model.domain.OmcSchedul;
import com.csun.cmny.provider.model.domain.OmcSchedulMonth;
import com.csun.cmny.provider.model.domain.OmcShifts;
import com.csun.cmny.provider.service.OmcPlanService;
import com.csun.cmny.provider.service.OmcShiftsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class OmcShiftsServiceImpl extends BaseService<OmcShifts> implements OmcShiftsService {

    @Resource
    private OmcShiftsMapper omcShiftsMapper;

    @Resource
    private OmcPlanService omcPlanService;

    @Override
    public Integer batchUpdate(List<OmcShifts> omcShiftsList) {
        int i = 0;
        //批量更新
        for(int j = omcShiftsList.size(); i <= j-1; i++){
            if(omcShiftsList.get(i).getId() != null && omcShiftsList.get(i).getId() > 0){
                int ret = omcShiftsMapper.updateByPrimaryKeySelective(omcShiftsList.get(i));
                if(ret <= 0){
                    throw new OmcBizException(ErrorCodeEnum.OMC10035003);
                }
            }
        }
        return i;
    }

    @Override
    public Integer deleteByPlanId(Long planId) {
        OmcShifts example = new OmcShifts();
        example.setPlanid(planId);
        int ret = omcShiftsMapper.delete(example);
        return ret;
    }

    @Override
    public List<OmcPlan> setShifts(List<OmcPlan> omcPlanList) {
        for(int i = 0, j = omcPlanList.size()-1; i<=j; i++){
            OmcShifts omcShifts = new OmcShifts();
            omcShifts.setPlanid(omcPlanList.get(i).getId());
            omcPlanList.get(i).setShiftsList(omcShiftsMapper.select(omcShifts));
        }
        return omcPlanList;
    }

    @Override
    public List<OmcSchedul> setShiftsOfSchedule(List<OmcSchedul> omcSchedulList) {
        for(int i = 0, j = omcSchedulList.size()-1; i<=j; i++){
            omcSchedulList.get(i).setOmcShifts(omcShiftsMapper.selectByPrimaryKey(omcSchedulList.get(i).getShiftsId()));
        }
        return omcSchedulList;
    }

    @Override
    public Integer deleteById(Long shiftId) {
        OmcShifts omcShifts = selectByKey(shiftId);
        if(omcShifts != null){
            //先校验该方案是否被使用，若使用过无法删除
            OmcPlan omcPlan = omcPlanService.selectByKey(omcShifts.getPlanid());
            if(omcPlan != null && omcPlan.getIsUsed() > 0){
                throw new OmcBizException(ErrorCodeEnum.OMC10035004);
            }
            return deleteByKey(shiftId);
        }else{
            throw new OmcBizException(ErrorCodeEnum.OMC10035010);
        }
    }
}
